<template>
    <div>
<!--      面包屑-->
        <Breadcrumb/>
<!--      卡片-->
      <el-card>
        <el-row>
          <el-col>
             <el-button type="success" @click="addCateDialog">添加分类</el-button>
          </el-col>
        </el-row>
<!--        表格-->
        <zk-table :data="cateList" :columns="columns" class="zktable"
        :selection-type="false" :expand-type="false" show-index index-text="#" border :show-row-hover="false"
        >
<!--          是否有效-->
          <template slot="isok" slot-scope="scope">
             <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color: lightgreen;"></i>
            <i class="el-icon-error" v-else style="color: red;"></i>
          </template>
<!--            排序-->
          <template v-slot:order="scope">
              <el-tag v-if="scope.row.cat_level===0">
                  一级
              </el-tag>
            <el-tag type="success" size="mine" v-else-if="scope.row.cat_level===1">
              二级
            </el-tag>
            <el-tag type="warning" size="mine" v-else>
              三级
            </el-tag>
          </template>
<!--          操作-->
          <template v-slot:opt="scope">
             <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除</el-button>
          </template>
        </zk-table>
<!--        分页区域-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </el-card>
      <!--     增加分类对话框-->
      <el-dialog
          title="增加分类"
          :visible.sync="addCatDialogVisible"
          width="40%"
          @close="addDialogClosed" >
        <el-form ref="addCateFormRef" :model="addCateForm" label-width="80px" :rules="addCateFormRules" >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类" >
              <el-cascader
                  change-on-select
                  expand-trigger="hover"
                  v-model="selectedKeys"
                  :props="cascaderProps"
                  :options="parentCateList"
                  @change="parentCateChange" ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCatDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>


<!--      //修改分类-->
      <el-dialog
          title="修改分类"
          :visible.sync="editCatDialogVisible"
          width="40%"
          @close="editDialogClosed" >
        <el-form ref="addCateFormRef" :model="editCateForm" label-width="80px" :rules="addCateFormRules" >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCatDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>

      </el-dialog>

    </div>
</template>

<script>
import Breadcrumb from "@/components/Breadcrumb";
export default {
  name: "Cate",
  components: {
    Breadcrumb,

  },
  data(){
    return{
      editCatDialogVisible:false,
      cateList:[],
      queryInfo:{
        type:3,
        pagenum:1,
        pagesize:3
      },
      total:0,
      addCatDialogVisible:false,
      //为zk—table 指定列的定义
      columns:[{
        label:"分类名称",
        prop:'cat_name'
      },{
        label: '是否有效',
        //表示，将当前列定义为模版列
        type:'template',
        //表示当前这一列使用模版名称
        template:'isok'
      },{
        label: '排序',
        type:'template',
        template: 'order'
      },{
        label: '操作',
        type: 'template',
        template: 'opt'
      }],
      editCateForm:{

      },
      addCateForm:{
        //将要添加的分类名称
        cat_name:'',
        //父级分类id
        cat_pid:0,
        //添加等级默认添加的是1级分类
        cat_level:0
      },
      addCateFormRules:{
        cat_name: [{required: true, message: "请输入分类名称", trigger: "blur"},
        ]},
      //父级分类的列表
      parentCateList:[],
      //指定级联选择器的配置对象
      cascaderProps:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
      },
      //选中的父级分类的id数组
      selectedKeys:[]
    }
  },
  created() {
    this.getCateList()
  },
  methods:{
    async deleteCate(id) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const {data: res} = await this.axios.delete(`categories/${id}`);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.getCateList()
        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },

    async showeditDialog(row) {
      this.editCatDialogVisible = true;
      try {
        const {data: res} = await this.axios.get(`categories/${row.cat_id}`);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.editCateForm = res.data
      } catch (e) {
        this.$message.error("服务器出错请联系管理员")
      }
    },
    editCate(){
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) {
          return;
        }
        try {
          const {data: res} = await this.axios.put('categories/'+this.editCateForm.cat_id, {cat_name:this.editCateForm.cat_name});
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.editCatDialogVisible=false;
          this.getCateList()
          this.$message.success(res.meta.msg)

        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      })
    },
    addCate(){
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) {
          return;
        }
        try {
          const {data: res} = await this.axios.post('categories',this.addCateForm);
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.addCatDialogVisible=false;
          this.getCateList()
          this.$message.success(res.meta.msg)
        } catch (e) {
          this.$message.error("服务器出错请联系管理员")
        }
      })
    },
    parentCateChange(){
      console.log(this.selectedKeys);
      //if selectedKeys数据中的length>0说明选中了父级分类
      if (this.selectedKeys.length>0){
        this.addCateForm.cat_pid=this.selectedKeys[this.selectedKeys.length-1]
        this.addCateForm.cat_level=this.selectedKeys.length;
        return
      }else {
        this.addCateForm.cat_pid=0
        this.addCateForm.cat_level=0
        return
      }
    },
    addCateDialog(){
      this.getParentCateList();
      this.addCatDialogVisible=true;
    },
    addDialogClosed(){
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys=[]
      this.addCateForm.cat_pid=0
      this.addCateForm.cat_level=0
    },
    handleSizeChange(newSize){
        this.queryInfo.pagesize=newSize;
        this.getCateList();
    },
    handleCurrentChange(newNum){
      this.queryInfo.pagenum=newNum;
      this.getCateList();

    },
    async getCateList() {
      try {
        const {data: res} = await this.axios.get(`categories`, {params: this.queryInfo});
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.cateList=res.data.result;
        this.total=res.data.total
      } catch (e) {
        this.$message.error(e)
      }
    },
    async getParentCateList() {
      try {
        const {data: res} = await this.axios.get(`categories`, {params: {type:2}});
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.parentCateList = res.data;
      } catch (e) {
        this.$message.error(e)
      }
    }
  }
}
</script>

<style scoped>
.zktable{
  margin-top: 10px;
}
.el-cascader{
  width: 100%;
}
</style>
